class_name StateMachine
extends Node

@export var initState: CardState

var currentState: CardState
var states := {}

# 当当前所有状态加入状态机，并将状态与ui挂载
func init(card: Card) -> void:
	for child in get_children():
		if child is CardState:
			states[child.state] = child
			child.transition.connect(
				onTransition
			)
			child.card = card
	if initState:
		initState.enter()
		currentState = initState

# 事件下放
func onInput(event: InputEvent) -> void:
	if currentState: currentState.onInput(event)
func onGuiInput(event: InputEvent) -> void:
	if currentState: currentState.onGuiInput(event)
func onMouseEntered() -> void:
	if currentState: currentState.onMouseEntered()
func onMouseExited() -> void:
	if currentState: currentState.onMouseExited()

# 状态流转
func onTransition(from: CardState, to: CardState.State) -> void:
	if from != currentState: return push_error("状态源不一致")
	var newState: CardState = states[to]
	if !newState: return push_error("要流转的状态不存在")

	if currentState: currentState.exit()
	newState.enter()
	currentState = newState
